<template>
  <div class="personal-box">
    <van-sticky>
      <van-nav-bar @click-left="goBack" title="员工档案" left-arrow>
      </van-nav-bar>
    </van-sticky>
    <div v-if="personInfo" class="ly-border-card userinfo-box">
      <div class="left-img">
        <van-image
          width="6rem"
          height="6rem"
          fit="cover"
          position="center"
          :src="personInfo.profilepicture"
        >
          <template v-slot:loading>
            <span class="placeholder-avatar">{{ personInfo.name }}</span>
          </template>
          <template v-slot:error>
            <span class="placeholder-avatar">{{ personInfo.name }}</span>
          </template>
        </van-image>
      </div>
      <div class="person-info">
        <div class="name-info">
          <div class="name-info-left">
            <span class="name">{{ personInfo.name }}</span>
            <span class="gender-info" :class="{ girl: personInfo.gender == 2 }">
              <i
                class="iconfont"
                :class="personInfo.gender == 1 ? 'icon-boy' : 'icon-girl'"
              ></i>
            </span>
          </div>
          <div class="work-position" style="font-size: 12px">
            <span>{{ personInfo.workposition }}</span>
            <span> | </span>
            <span>{{ personInfo.level }}</span>
          </div>
        </div>
        <div class="font-sub van-ellipsis">
          直接上级：{{ personInfo.directlyleader }}
        </div>
        <div class="font-sub van-ellipsis">
          {{ personInfo.departname_up }}-{{ personInfo.departname }}
        </div>
      </div>
    </div>
    <div v-else class="ly-border-card">
      <EmptyComp description="暂无个人信息"></EmptyComp>
    </div>

    <!-- //基本信息 -->
    <div id="basic" class="basic-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="personInfoLoading">
        <div class="card-title">
          <span class="color-line"></span>
          <span>基本信息</span>
        </div>
        <template v-if="basicInfo">
          <van-row
            style="margin-top: 20px; padding-left: 8px"
            :gutter="[10, 20]"
          >
            <van-col span="12">
              <span>年龄：</span><span>{{ basicInfo.age }}</span>
            </van-col>
            <van-col span="12">
              <span>出生日期：</span
              ><span>{{ formatDate(basicInfo.birthday) }}</span>
            </van-col>
            <van-col span="12">
              <span>籍贯：</span><span>{{ basicInfo.nativeplace }}</span>
            </van-col>
            <van-col span="12">
              <span>民族：</span><span>{{ basicInfo.nationality }}</span>
            </van-col>
            <van-col span="12">
              <span>最高学历：</span
              ><span>{{ basicInfo.highesteducationlevel }}</span>
            </van-col>
            <van-col span="12">
              <span>入职日期：</span
              ><span>{{ formatDate(basicInfo.entrytime) }}</span>
            </van-col>
          </van-row>
        </template>
        <EmptyComp v-else description="暂无基本信息"></EmptyComp>
      </van-skeleton>
    </div>

    <!-- //教育经历 -->
    <div id="education" class="education-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="personInfoLoading">
        <div class="card-title">
          <span class="color-line"></span>
          <span>教育经历</span>
        </div>
        <template v-if="eductionInfoList.length">
          <van-collapse v-model="activeEducationNames">
            <van-collapse-item
              :name="item.uuid"
              v-for="item in eductionInfoList"
              :key="item.educationBg"
            >
              <template #title>
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <span class="require-dot">
                    <span
                      >{{ formatDate(item.begda) }}~{{
                        formatDate(item.endda)
                      }}</span
                    >
                  </span>
                  <span>{{ item.educationbg }}</span>
                </div>
              </template>
              <div class="collapse-item-text van-ellipsis">
                学校：{{ item.schoolname }}
              </div>
              <div class="collapse-item-text van-ellipsis">
                专业名称：{{ item.majorname || "不详" }}
              </div>
            </van-collapse-item>
          </van-collapse>
        </template>
        <EmptyComp v-else description="暂无教育经历"></EmptyComp>
      </van-skeleton>
    </div>

    <!-- //工作经历 -->
    <div id="work" class="work-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="workInfoLoading">
        <div class="card-title">
          <span class="color-line"></span>
          <span>工作履历</span>
        </div>
        <template v-if="workInfoList.length">
          <van-collapse v-model="activeWorkNames">
            <van-collapse-item
              :name="item.uuid"
              v-for="(item, index) in showWorkInfoList"
              :key="index"
            >
              <template #title>
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <span class="require-dot">
                    <span>{{ item.startTime }}~{{ item.endTime }}</span>
                    <span v-if="item.workYears"
                      >({{ Number(item.workYears).toFixed(1) }}年)</span
                    >
                  </span>
                  <span class="van-ellipsis">{{ item.workPosition }}</span>
                </div>
              </template>
              <div class="collapse-item-text van-ellipsis">
                公司名称：{{ item.companyName }}
              </div>
              <div class="collapse-item-text van-ellipsis">
                部门名称：{{ item.departName }}
              </div>
            </van-collapse-item>
          </van-collapse>
          <div class="show-more" v-if="workInfoList.length > 2">
            <span @click.stop="onClickShowMoreWork" class="btn-text">
              {{ sliceWorkIndex <= 2 ? "查看更多" : "收起更多" }}
            </span>
          </div>
        </template>
        <EmptyComp v-else description="暂无工作履历"></EmptyComp>
      </van-skeleton>
    </div>
    <!-- 绩效考核 -->
    <div id="performance" class="performance-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="personInfoLoading">
        <div class="card-title flex-box">
          <div>
            <span class="color-line"></span>
            <span>{{
              performanceType === "year" ? "年度绩效考核" : "近12个月绩效考核"
            }}</span>
          </div>
          <div class="performance-type-box">
            <span
              class="performance-type"
              :class="{ active: performanceType === 'year' }"
              @click.stop="performanceType = 'year'"
            >
              年度
            </span>
            <span
              class="performance-type"
              :class="{ active: performanceType === 'month' }"
              @click.stop="performanceType = 'month'"
            >
              月度
            </span>
          </div>
        </div>
        <section class="year-section" v-show="performanceType === 'year'">
          <template v-if="yearPerformanceList.length">
            <van-row
              style="margin-top: 20px"
              :gutter="[10, 10]"
              v-for="item in yearPerformanceList"
              :key="item.time"
            >
              <van-col span="14">
                <span class="require-dot">
                  <span>{{ formatDate(item.begda) }}</span>
                  <span> ~ </span>
                  <span>{{ formatDate(item.endda) }}</span>
                </span>
              </van-col>
              <van-col span="10" style="text-align: center">
                {{ item.performancelevel }}</van-col
              >
            </van-row>
          </template>
          <EmptyComp v-else description="暂无年度绩效"></EmptyComp>
        </section>
        <section v-show="performanceType === 'month'" class="month-section">
          <template v-if="Object.keys(lineChartOptions).length">
            <LineChartComp
              :height="'300px'"
              :option="lineChartOptions"
            ></LineChartComp>
          </template>
          <EmptyComp v-else description="暂无月度绩效"></EmptyComp>
        </section>
      </van-skeleton>
    </div>
    <!-- 人才盘点 -->
    <div id="talent" class="talent-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="talentInfoLoading">
        <div class="card-title">
          <span class="color-line"></span>
          <span>人才盘点</span>
        </div>
        <template v-if="talentInfoList.length">
          <van-row
            style="margin-top: 20px"
            :gutter="[10, 10]"
            v-for="item in showTalentInfoList"
            :key="item.evaluateTime"
          >
            <van-col span="12">
              <div class="require-dot">
                <span>{{ item.evaluateTime }}</span>
              </div>
            </van-col>
            <van-col
              span="12"
              :style="{
                color:
                  item.colorFlag === 'red'
                    ? '#611616'
                    : item.colorFlag === 'green'
                    ? '#1e5c37'
                    : '#d9a600',
              }"
            >
              {{ item.evaluateText }}
            </van-col>
          </van-row>
          <div class="show-more" v-if="talentInfoList.length > 2">
            <span @click.stop="onClickShowMoreTalent" class="btn-text">
              {{ sliceTalentIndex <= 2 ? "查看更多" : "收起更多" }}
            </span>
          </div>
        </template>
        <EmptyComp v-else description="暂无人才盘点"></EmptyComp>
      </van-skeleton>
    </div>
    <!-- //任职信息 -->
    <div id="employment" class="employment-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="employmentInfoLoading">
        <div class="card-title">
          <span class="color-line"></span>
          <span>任职信息</span>
        </div>
        <template v-if="employmentInfoList.length">
          <van-collapse v-model="activeEmployMentNames">
            <div class="vertical-line"></div>
            <van-collapse-item
              :name="item.uuid"
              v-for="(item, index) in showEmploymentInfoList"
              :key="index"
            >
              <template #title>
                <span class="work-icon">
                  <i
                    v-if="index === 0"
                    class="iconfont icon-dangqianrenzhi"
                  ></i>
                  <span v-else class="grey-dot"></span>
                </span>
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <span>
                    <span>{{ item.startTime }}~{{ item.endTime }}</span>
                    <van-tag
                      type="primary"
                      :color="index === 0 ? '#ffe6da' : '#cecece'"
                      text-color="#ffffff"
                      style="margin-left: 4px"
                      >{{ item.employmentTag }}</van-tag
                    >
                  </span>
                  <span>{{ item.workPosition }}</span>
                </div>
              </template>
              <div class="collapse-item-text van-ellipsis">
                职级：{{ item.levelName }}
              </div>
              <div class="collapse-item-text van-ellipsis">
                直接上级：{{ item.directlyLeader }}
              </div>
              <div class="collapse-item-text van-ellipsis">
                组织：{{ item.departName }}
              </div>
            </van-collapse-item>
          </van-collapse>
          <div class="show-more" v-if="employmentInfoList.length > 2">
            <span @click.stop="onClickShowMoreEmployment" class="btn-text">
              {{ sliceEmploymentIndex <= 2 ? "查看更多" : "收起更多" }}
            </span>
          </div>
        </template>
        <EmptyComp v-else description="暂无任职信息"></EmptyComp>
      </van-skeleton>
    </div>
    <!-- //奖惩信息 -->
    <div id="reward" class="reward-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="rewardListLoading">
        <div class="card-title">
          <span class="color-line"></span>
          <span>奖惩信息</span>
        </div>
        <template v-if="rewardList.length">
          <van-row
            style="margin-top: 20px"
            :gutter="[10, 10]"
            v-for="item in showRewardList"
            :key="item.id"
          >
            <van-col span="20">
              <span class="require-dot"
                >{{ item.rewardTime }}
                <span style="margin-left: 20px">{{ item.rewardText }}</span>
              </span>
            </van-col>
            <van-col span="4">
              <div class="evaluate-box">
                <span @click.stop="previewReward(item)" class="preview-btn"
                  >查看详情</span
                >
              </div>
            </van-col>
          </van-row>
          <div class="show-more" v-if="rewardList.length > 3">
            <span @click.stop="onClickShowMoreReward" class="btn-text">
              {{ sliceRewardIndex <= 3 ? "查看更多" : "收起更多" }}
            </span>
          </div>
          <van-dialog
            v-model:show="showRewardDialog"
            class="reward-custom-dialog"
            @closed="rewardDialogClosed"
          >
            <template #default>
              <div class="reward-content hx-scroll">
                <div class="reward-item">
                  <h3 class="title">具体事迹</h3>
                  <p class="content">
                    &nbsp;&nbsp;&nbsp;&nbsp;{{
                      currentPreviewReward.rewardContent
                    }}
                  </p>
                </div>
                <div class="reward-item">
                  <h3 class="title">奖惩依据</h3>
                  <p class="content">
                    &nbsp;&nbsp;&nbsp;&nbsp;{{ currentPreviewReward.according }}
                  </p>
                </div>
              </div>
            </template>
          </van-dialog>
        </template>
        <EmptyComp v-else description="暂无奖惩信息"></EmptyComp>
      </van-skeleton>
    </div>
    <!-- //测评信息 -->
    <div id="evaluating" class="evaluating-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="evaluateListLoading">
        <div class="card-title">
          <span class="color-line"></span>
          <span>测评</span>
        </div>
        <template v-if="evaluateList.length">
          <van-row
            style="margin-top: 20px"
            :gutter="[10, 10]"
            v-for="item in showEvaluateList"
            :key="item.id"
          >
            <van-col span="12">
              <span class="require-dot">{{ item.name }}</span>
            </van-col>
            <van-col span="12">
              <div class="evaluate-box">
                <span>{{ item.score }}</span>
                <van-icon name="eye" class="eye-icon"></van-icon>
                <span @click.stop="previewEvaluate(item)" class="preview-btn"
                  >预览</span
                >
              </div>
            </van-col>
          </van-row>
          <div class="show-more" v-if="evaluateList.length > 2">
            <span @click.stop="onClickShowMoreEvaluate" class="btn-text">
              {{ sliceEvaluateIndex <= 2 ? "查看更多" : "收起更多" }}
            </span>
          </div>
        </template>
        <EmptyComp v-else description="暂无测评信息"></EmptyComp>
      </van-skeleton>
    </div>
    <!-- 亲属关系 -->
    <div id="relation" class="relation-info card-box ly-border-card">
      <van-skeleton title :row="3" :loading="personInfoLoading">
        <div class="card-title">
          <span class="color-line"></span>
          <span>亲属关系</span>
        </div>
        <template v-if="relationInfoList.length">
          <van-row
            style="margin-top: 25px"
            :gutter="[10, 15]"
            v-for="item in relationInfoList"
            :key="item.name"
          >
            <van-col span="12">
              <span class="require-dot">姓名：{{ item.name }} </span>
            </van-col>
            <van-col span="12">关系： {{ item.relation }}</van-col>
            <van-col span="24">
              <div class="remark-box">
                <span class="remark-title">亲属关系描述： </span>
                <span>{{ item.remark }}</span>
              </div>
            </van-col>
          </van-row>
        </template>
        <EmptyComp v-else description="暂无亲属关系"></EmptyComp>
      </van-skeleton>
    </div>
    <div
      class="side-emit"
      v-show="!sideBarShow"
      @click.stop="sideBarShow = true"
    >
      <van-icon name="arrow-double-left" />
    </div>
    <div class="sidebar-box" v-show="sideBarShow">
      <div class="close-side" @click.stop="sideBarShow = false">
        <van-icon name="arrow-double-right" />
      </div>
      <van-sidebar v-model="currentSideBar" @change="onSidebarChange">
        <van-sidebar-item
          v-for="item in sideBarList"
          :key="item.id"
          :title="item.label"
        />
      </van-sidebar>
    </div>
    <van-back-top right="20" bottom="20" />
  </div>
</template>
<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  computed,
  nextTick,
  getCurrentInstance,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import LineChartComp from "@/components/LineChartComp.vue";
import personApi from "@/api/personApi";
import { useUserStore } from "@/stores/userInfo";
import { usePublicStore } from "@/stores/publicInfo";
import EmptyComp from "@/components/EmptyComp.vue";
import sapRequest from "@/api/sapRequest";
const userStore = useUserStore();
const publicStore = usePublicStore();
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
function goBack() {
  router.go(-1);
}
const getUUID = proxy.$utils.getUUID;
const personInfoLoading = ref(true);
const personInfo = ref(null);
const basicInfo = ref(null);
const activeEducationNames = ref([]);
const eductionInfoList = ref([]);
//工作履历相关
const workInfoLoading = ref(true);
const activeWorkNames = ref([]);
const workInfoList = ref([]);
const sliceWorkIndex = ref(2);
const showWorkInfoList = computed(() => {
  return workInfoList.value.slice(0, sliceWorkIndex.value);
});
function onClickShowMoreWork() {
  sliceWorkIndex.value =
    sliceWorkIndex.value > 2 ? 2 : workInfoList.value.length;
}

function setUUID(arr) {
  if (Array.isArray(arr)) {
    return arr.map((el) => {
      return {
        ...el,
        uuid: getUUID(),
      };
    });
  } else {
    return arr;
  }
}

//获取工作履历
function getOutEmploy(workNo) {
  personApi
    .getOutEmploy({
      workNo,
    })
    .then((res) => {
      if (res.code === 200) {
        workInfoList.value = setUUID(res.result) || [];
        activeWorkNames.value = workInfoList.value
          .slice(0, 2)
          .map((el) => el.uuid);
      } else {
        workInfoList.value = [];
        showToast(res.message);
      }
    })
    .catch((error) => {
      showFailToast(error.message);
    })
    .finally(() => {
      workInfoLoading.value = false;
    });
}

//绩效考核相关
const performanceType = ref("month");
const yearPerformanceList = ref([]);
function setMonthPerformance(ydjx) {
  if (Array.isArray(ydjx) && ydjx.length) {
    const xData = ydjx.map((el) => `${el.month}月`);
    const yearStr = ydjx[0]["year"] || "";

    const numberToChinese = {
      1: "未考核",
      2: "NI",
      3: "S-",
      4: "S",
      5: "S+",
      6: "E",
    };
    const chineseToNumber = {
      未考核: 1,
      NI: 2,
      "S-": 3,
      S: 4,
      "S+": 5,
      E: 6,
    };
    const yData = ydjx.map((el) => {
      return chineseToNumber[el.performancelevel] || 0;
    });

    lineChartOptions.value = {
      grid: {
        left: "10%",
        right: "10px",
        top: "10px",
        bottom: "15%",
      },
      xAxis: {
        type: "category",
        data: xData,
        name: "月份",
        axisLabel: {
          interval: 0, // 强制显示所有标签
          margin: 10, // 调整标签与轴线的距离
          overflow: "break", // 文字过长时换行
          fontSize: 10,
          color: "#777e8c",
          formatter: (value, index) => {
            if (index === 0) {
              return `{a|${value}}\n▼\n{b|${yearStr}}`; // 使用富文本换行
            }
            return value;
          },
          rich: {
            b: {
              fontSize: 10,
              color: "#505050",
              padding: [0, 0, 0, 0], // 调整年份标签的位置
            },
          },
        },
      },
      yAxis: {
        type: "value",
        name: "绩效等级",
        min: 0,
        max: 6,
        interval: 1, // 刻度间隔为 1
        splitNumber: 6, // 分段数为 6
        axisLabel: {
          formatter: (value) => {
            return numberToChinese[value] || "";
          },
        },
        splitLine: {
          show: false, // 不显示 Y 轴对应点的横线
        },
      },
      series: [
        {
          name: "绩效等级",
          type: "line",
          data: yData,
          smooth: true,
          lineStyle: {
            color: "#ff9b6d",
            width: 2,
          },
          itemStyle: {
            color: "#ffc8b0",
          },
        },
      ],
    };
  } else {
    lineChartOptions.value = {};
  }
}
// 定义图表配置项
const lineChartOptions = ref({});
//人才盘点相关
const talentInfoLoading = ref(false);
const sliceTalentIndex = ref(2);
const talentInfoList = ref([]);
const showTalentInfoList = computed(() => {
  return talentInfoList.value.slice(0, sliceTalentIndex.value);
});
function onClickShowMoreTalent() {
  sliceTalentIndex.value =
    sliceTalentIndex.value > 2 ? 2 : talentInfoList.value.length;
}

function getInventory(workNo) {
  talentInfoLoading.value = true;
  personApi
    .getInventory({
      workNo,
    })
    .then((res) => {
      if (res.code === 200) {
        //人才盘点倒序，先前端处理
        talentInfoList.value = (res.result || []).reverse();
      } else {
        talentInfoList.value = [];
        showToast(res.message);
      }
    })
    .catch((error) => {
      showFailToast(error.message);
    })
    .finally(() => {
      talentInfoLoading.value = false;
    });
}

//任职信息
const employmentInfoLoading = ref(true);
const activeEmployMentNames = ref([]);
const employmentInfoList = ref([]);
const sliceEmploymentIndex = ref(2);
const showEmploymentInfoList = computed(() => {
  return employmentInfoList.value.slice(0, sliceEmploymentIndex.value);
});
function onClickShowMoreEmployment() {
  sliceEmploymentIndex.value =
    sliceEmploymentIndex.value > 2 ? 2 : employmentInfoList.value.length;
}

//获取任职信息
function getInEmploy(workNo) {
  employmentInfoLoading.value = true;
  personApi
    .getInEmploy({
      workNo,
    })
    .then((res) => {
      if (res.code === 200) {
        employmentInfoList.value = setUUID(res.result) || [];
        activeEmployMentNames.value = employmentInfoList.value
          .slice(0, 2)
          .map((el) => el.uuid);
      } else {
        employmentInfoList.value = [];
        activeEmployMentNames.value = [];
        showToast(res.message);
      }
    })
    .catch((error) => {
      showFailToast(error.message);
    })
    .finally(() => {
      employmentInfoLoading.value = false;
    });
}
//奖惩信息
const rewardListLoading = ref(false);
const sliceRewardIndex = ref(3);
const rewardList = ref([]);
const showRewardList = computed(() => {
  return rewardList.value.slice(0, sliceRewardIndex.value);
});
function onClickShowMoreReward() {
  sliceRewardIndex.value =
    sliceRewardIndex.value > 3 ? 3 : rewardList.value.length;
}
//查看奖惩详情
const showRewardDialog = ref(false);
//当前预览详情item
const currentPreviewReward = ref({});
function getRewards(workNo) {
  rewardListLoading.value = true;
  personApi
    .getRewards({
      workNo,
    })
    .then((res) => {
      if (res.code === 200) {
        rewardList.value = res.result || [];
      } else {
        rewardList.value = [];
        showToast(res.message);
      }
    })
    .catch((error) => {
      showFailToast(error.message);
    })
    .finally(() => {
      rewardListLoading.value = false;
    });
}
function previewReward(item) {
  showRewardDialog.value = true;
  currentPreviewReward.value = item;
}

function rewardDialogClosed() {
  currentPreviewReward.value = {};
}

//测评
const evaluateListLoading = ref(false);
const sliceEvaluateIndex = ref(2);
const evaluateList = ref([]);
const showEvaluateList = computed(() => {
  return evaluateList.value.slice(0, sliceEvaluateIndex.value);
});
function onClickShowMoreEvaluate() {
  sliceEvaluateIndex.value =
    sliceEvaluateIndex.value > 2 ? 2 : evaluateList.value.length;
}
function getEvaluation(workNo) {
  evaluateListLoading.value = true;
  personApi
    .getEvaluation({
      workNo,
    })
    .then((res) => {
      if (res.code === 200) {
        evaluateList.value = res.result || [];
      } else {
        evaluateList.value = [];
        showToast(res.message);
      }
    })
    .catch((error) => {
      showFailToast(error.message);
    })
    .finally(() => {
      evaluateListLoading.value = false;
    });
}
function previewEvaluate(item) {
  if (item.url) {
    window.open(item.url, "_blank");
  } else {
    showToast("未获取到预览地址，无法预览");
  }
}
// 亲属关系
const relationInfoList = ref([]);
//右侧导航栏相关
const sideBarShow = ref(false);
const currentSideBar = ref(0);
const sideBarList = ref([
  { id: "basic", label: "基本信息" },
  { id: "education", label: "教育经历" },
  { id: "work", label: "工作履历" },
  { id: "performance", label: "绩效考核" },
  { id: "talent", label: "人才盘点" },
  { id: "employment", label: "任职信息" },
  { id: "reward", label: "奖惩信息" },
  { id: "evaluating", label: "测评信息" },
  { id: "relation", label: "亲属关系" },
]);
function onSidebarChange(sideIndex) {
  currentSideBar.value = sideIndex;
  updateHash(sideIndex);
  scrollToSection(sideIndex);
}
// 更新 URL 的 hash
function updateHash(index) {
  const hash = `#${sideBarList.value[index]["id"]}`;
  if (window.location.hash !== hash) {
    // window.location.hash = hash; // 更新 URL 的 hash
    // 使用 history.replaceState 替换 hash，不触发滚动
    history.replaceState(null, null, hash);
  }
}
function scrollToSection(index) {
  const sectionId = `#${sideBarList.value[index]["id"]}`;
  const sectionElement = document.querySelector(sectionId);
  if (sectionElement) {
    sectionElement.scrollIntoView({ block: "center", behavior: "smooth" });
  }
}
// 监听 hash 变化
const handleHashChange = () => {
  const hash = window.location.hash.slice(1);
  const index = sideBarList.value.findIndex((item) => item.id === hash);
  if (index !== -1 && index !== currentSideBar.value) {
    currentSideBar.value = index;
    scrollToSection(index);
  }
};
const observer = new IntersectionObserver(
  (entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const index = sideBarList.value.findIndex(
          (item) => item.id === entry.target.id
        );
        if (index !== -1) {
          nextTick(() => {
            currentSideBar.value = index;
          });
        }
      }
    });
  },
  { threshold: 1 } // 当 100% 的模块进入视口时触发
);

function formatDate(dateStr) {
  return dateStr.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");
}

function getPersonInfo(workNo) {
  personInfoLoading.value = true;
  const params = {
    IM_SYSID: "YGDA", //系统标识，员工档案
    IM_OBJID: workNo, //组织编码
    //"IM_PERNR": "10000270", //操作人工号
    IM_DATE: publicStore.searchDateStr, //查询日期
    //    "IM_LANGU": "", //语言，非必填，
  };
  sapRequest
    .personInfo(params)
    .then((res) => {
      if (Array.isArray(res) && res.length) {
        const {
          jbxx = {},
          jyjl = [],
          ndjx = [],
          qsgx = [],
          ydjx = [],
          ygxx = {},
        } = res[0];
        personInfo.value = ygxx; //员工信息
        basicInfo.value = jbxx; //基本消息
        //教育经历
        eductionInfoList.value = setUUID(jyjl) || [];
        activeEducationNames.value = eductionInfoList.value
          .slice(0, 2)
          .map((el) => el.uuid);

        relationInfoList.value = qsgx; //亲属关系

        //年度绩效
        yearPerformanceList.value = ndjx;
        //月度绩效
        setMonthPerformance(ydjx);
      } else {
        showToast(res.message || "获取员工档案失败！");
      }
    })
    .catch((error) => {
      showToast(error.message || "获取员工档案失败！");
    })
    .finally(() => {
      personInfoLoading.value = false;
    });
}

function init() {
  //优先取url上面的id 再取登录用户id
  const workNo = route.params.pid || userStore.userid;
  //工作经历
  getOutEmploy(workNo);
  //任职信息
  getInEmploy(workNo);
  //人才盘点
  getInventory(workNo);
  //测评信息
  getEvaluation(workNo);
  //奖惩信息
  getRewards(workNo);
  //sap接口请求员工档案
  getPersonInfo(workNo);
}
onMounted(() => {
  init();
  window.addEventListener("hashchange", handleHashChange);
  // 初始化时根据 hash 定位
  nextTick(() => {
    sideBarList.value.forEach((item) => {
      const sectionElement = document.getElementById(item.id);
      if (sectionElement) {
        observer.observe(sectionElement);
      }
    });
    if (window.location.hash) {
      const hash = window.location.hash.slice(1);
      const index = sideBarList.value.findIndex((item) => item.id === hash);
      if (index !== -1) {
        currentSideBar.value = index;
        scrollToSection(index);
      }
    }
  });
});
onUnmounted(() => {
  observer.disconnect();
  window.removeEventListener("hashchange", handleHashChange);
});
</script>
<style lang="scss" scoped>
.personal-box {
  padding-bottom: 20px;
  color: #505050;

  :deep(.van-cell:after) {
    border: none;
  }

  .userinfo-box {
    margin-top: 10px;
    display: flex;
    .left-img {
      :deep(.van-image) {
        .placeholder-avatar {
          height: 100%;
          width: 100%;
          background-color: #007fff;
          color: #fff;
          font-size: 16px;
          text-align: center;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 8px;
        }
      }
    }
  }
  .person-info {
    margin-left: 10px;
    flex: 1;
    width: 1px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .name-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      &-left {
        display: flex;
        align-items: center;
      }
      .gender-info {
        width: 16px;
        height: 16px;
        text-align: center;
        line-height: 16px;
        border-radius: 50%;
        background-color: $skyBlue;
        margin-left: 4px;
        &.girl {
          background-color: #c79f62;
        }
        .iconfont {
          font-size: 12px;
          color: #fff;
        }
      }
    }
    .font-sub {
      font-size: 12px;
      color: #808080;
    }
    .name {
      font-size: 16px;
      font-weight: 600;
    }
  }
  .card-box {
    margin-top: 10px;
    position: relative;
    overflow: hidden;
    &::before {
      content: ""; /* 伪元素必须设置content */
      position: absolute; /* 绝对定位 */
      top: 0;
      right: 0;
      width: 50px;
      height: 50px;
      border-bottom-left-radius: 100%;
      background: linear-gradient(
        210deg,
        rgba(253, 241, 233, 100),
        rgba(255, 255, 255, 100) 60%
      );
      pointer-events: none; /* 确保伪元素不会干扰交互 */
    }
    .card-title {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      &.flex-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .color-line {
        display: inline-block;
        width: 3px;
        height: 16px;
        border-radius: 4px;
        background-color: $theme-color;
        margin-right: 4px;
        vertical-align: top;
      }
      span {
        font-size: 16px;
        font-weight: 600;
      }
    }
  }
  // :deep(.van-collapse-item) {
  //   .van-collapse-item__title--expanded .van-cell__right-icon:before {
  //     transform: rotate(-180deg);
  //   }
  // }
  .employment-info {
    .vertical-line {
      position: absolute;
      left: -1px;
      top: 10px;
      bottom: 10px;
      border: 1px dashed $font-color-gray-5;
      z-index: 1;
    }
    :deep(.van-collapse-item) {
      z-index: 2;
      & .van-cell {
        padding: 10px;
        overflow: visible;
        .work-icon {
          position: absolute;
          height: 24px;
          width: 12px;
          line-height: 24px;
          text-align: center;
          left: -6px;
          background-color: #fff;
          .iconfont {
            font-size: 12px;
            color: $theme-color;
            vertical-align: top;
          }
          .grey-dot {
            display: inline-block;
            vertical-align: middle;
            background-color: $font-color-tips;
            box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
            width: 6px;
            height: 6px;
            border-radius: 50%;
          }
        }
      }
    }
  }
  .performance-info {
    .performance-type-box {
      display: flex;
      align-items: center;
      z-index: 2;
      // margin-right: 40px;
      .performance-type {
        padding: 4px;
        color: $font-color-tips;
        border-radius: 6px;
        font-weight: 400;
        margin-left: 4px;
        box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
        border: 1px solid $font-color-gray-3;
        font-size: 12px;
        cursor: pointer;

        &.active {
          color: $theme-color;
          font-weight: bold;
        }
      }
    }
  }
  .show-more {
    margin-top: 20px;
    text-align: center;
    .btn-text {
      padding: 4px;
      cursor: pointer;
      color: $theme-color;
    }
  }

  .side-emit {
    position: fixed;
    right: 20px;
    bottom: 70px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: var(--van-back-top-size);
    height: var(--van-back-top-size);
    z-index: var(--van-back-top-z-index);
    cursor: pointer;
    color: var(--van-back-top-text-color);
    border-radius: var(--van-radius-max);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
    transition: var(--van-duration-base) cubic-bezier(0.25, 0.8, 0.5, 1);
    background-color: var(--van-back-top-background);
    .van-icon {
      font-size: var(--van-back-top-icon-size);
      font-weight: var(--van-font-bold);
    }
  }

  .sidebar-box {
    position: fixed;
    right: 10px;
    top: 50%;
    transform: translate3d(0, -50%, 0);
    opacity: 0.8;
    z-index: 99;

    .close-side {
      position: absolute;
      top: 50%;
      transform: translate3d(0, -50%, 0);
      left: -10px;
      display: flex;
      align-items: center;
      justify-content: center;
      height: var(--van-back-top-size);
      z-index: var(--van-back-top-z-index);
      cursor: pointer;
      color: var(--van-back-top-text-color);
      border-radius: var(--van-radius-max);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
      transition: var(--van-duration-base) cubic-bezier(0.25, 0.8, 0.5, 1);
      background-color: var(--van-back-top-background);

      .van-icon {
        font-size: var(--van-back-top-icon-size);
        font-weight: var(--van-font-bold);
      }
    }

    .van-sidebar-item {
      text-align: center;
    }
  }
  .collapse-item-text + .collapse-item-text {
    margin-top: 10px;
  }
  .require-dot {
    display: flex;
    align-items: center;
    &::before {
      content: " ";
      display: inline-block;
      vertical-align: middle;
      background-color: #ffc8b0;
      box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
      width: 6px;
      height: 6px;
      border-radius: 50%;
      margin-right: 6px;
    }
  }

  .evaluate-box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .eye-icon {
      color: $orange-color;
      margin-left: 4px;
      margin-right: 10px;
      flex-shrink: 0;
    }
    .preview-btn {
      font-size: 12px;
      color: $orange-color;
      cursor: pointer;
      flex-shrink: 0;
    }
  }

  .remark-box {
    display: flex;
    .remark-title {
      margin-left: 10px;
      flex-shrink: 0;
    }
  }
}
.reward-custom-dialog {
  .reward-content {
    padding: 10px;
    max-height: 70vh;
    overflow: auto;
    .title {
      font-weight: bold;
    }
    .content {
      margin-top: 10px;
      margin-bottom: 20px;
      font-size: 12px;
      line-height: 16px;
      color: $font-color-normal;
      word-break: break-all;
    }
  }
}
</style>
